package com.ib.review.base.utils;

import com.ib.review.pojo.bo.ExcelData;
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class KnowledgeExcelReader {
    public static List<ExcelData> readExcel(MultipartFile file) throws IOException {
        List<ExcelData> dataList = new ArrayList<>();

        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = WorkbookFactory.create(inputStream)) {

            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            boolean isFirstRow = true;

            for (Row row : sheet) {
                // 跳过表头行
                if (isFirstRow) {
                    isFirstRow = false;
                    continue;
                }

                // 读取每列数据
                String knowledgeName = getCellValue(row.getCell(0));
                String knowledgeSynonym = getCellValue(row.getCell(1));
                String knowledgeDesc = getCellValue(row.getCell(2));

                // 检查是否为空行
                if (knowledgeName.isEmpty() || knowledgeSynonym.isEmpty()) {
                    break; // 遇到空行则停止处理
                }

                // 创建对象并添加到列表
                dataList.add(new ExcelData(knowledgeName, knowledgeSynonym, knowledgeDesc));
            }
        }

        return dataList;
    }

    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }

        return switch (cell.getCellType()) {
            case STRING -> cell.getStringCellValue();
            case NUMERIC -> String.valueOf((int) cell.getNumericCellValue());
            case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
            default -> "";
        };
    }
}
